package com.example.excelimport.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.excelimport.entity.User;
import com.example.excelimport.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class UserImportListener extends AnalysisEventListener<User> {

    private static final int BATCH_SIZE = 2000;
    private List<User> cachedDataList = new ArrayList<>(BATCH_SIZE);

    @Autowired
    private UserService userService;

    // 通过构造函数注入，避免Spring管理问题
    public UserImportListener(UserService userService) {
        this.userService = userService;
    }

    @Override
    public void invoke(User user, AnalysisContext context) {
        cachedDataList.add(user);
        // 达到BATCH_SIZE时，批量保存一次
        if (cachedDataList.size() >= BATCH_SIZE) {
            saveData();
            cachedDataList = new ArrayList<>(BATCH_SIZE);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 处理最后一批数据
        if (!cachedDataList.isEmpty()) {
            saveData();
        }
        log.info("Excel数据解析完成");
    }

    /**
     * 批量保存数据
     * 注意：这里每个批次都会开启新的事务
     */
    private void saveData() {
        userService.batchSaveWithTransaction(cachedDataList);
        log.info("成功导入 {} 条数据", cachedDataList.size());
    }
}